package org.example.sentinel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    @Autowired
    private IpMonitorService ipMonitorService;
    
    @ExceptionHandler(Exception.class)
    public Mono<Void> handleException(ServerWebExchange exchange, Exception ex) {
        String clientIp = getClientIp(exchange);
        
        // 记录异常IP
        return ipMonitorService.recordException(clientIp)
            .then(Mono.error(ex));
    }

    private String getClientIp(ServerWebExchange exchange) {
        // 实现获取真实客户端IP的逻辑
        // 示例：从X-Forwarded-For头获取
        String xff = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For");
        if (xff != null && !xff.isEmpty()) {
            return xff.split(",")[0].trim();
        }
        return exchange.getRequest().getRemoteAddress() != null ?
                exchange.getRequest().getRemoteAddress().getAddress().getHostAddress() : "unknown";
    }
}